<?php

namespace yifang\response;

use yifang\lib\Cookie;
use yifang\lib\View as BaseView;

/**
 * View Response
 */
class View extends Response
{
    /**
     * 输出参数
     * @var array
     */
    protected $options = [];

    /**
     * 输出变量
     * @var array
     */
    public $vars = [];  //插件中间件需要修改这个值,实现动态增减参数,protected=>public

    /**
     * 内容过滤
     * @var mixed
     */
    protected $filter;

    /**
     * 输出type
     * @var string
     */
    protected $contentType = 'text/html';

    /**
     * View对象
     * @var BaseView
     */
    protected $view;

    /**
     * 是否内容渲染
     * @var bool
     */
    protected $isContent = false;

    public function __construct(Cookie $cookie, BaseView $view,$data = '', int $code = 200)
    {
        $this->init($data, $code);
        $this->cookie = $cookie;
        $this->view = $view;
    }

    /**
     * 设置是否为内容渲染
     */
    public function isContent($content = true)
    {
        $this->isContent = $content;
        return $this;
    }

    /**
     * 处理数据
     */
    protected function output($data,$templatePath)
    {
        // 渲染模板输出
//        $this->view->filter($this->filter);
//        return $this->isContent ?$this->view->display($data, $this->vars) :$this->view->fetch($data, $this->vars);

        // 渲染模板输出
        $vars=array_merge(templateManage()->getVars(),$this->getVars());
        $content=ob_template($data,$vars,$templatePath);
        if ($this->filter) {
            $content = call_user_func_array($this->filter, [$content]);
        }
        return $content;
    }

    /**
     * 获取视图变量
     */
    public function getVars($name = null)
    {
        if (is_null($name)) {
            return $this->vars;
        } else {
            return $this->vars[$name] ?? null;
        }
    }

    /**
     * 模板变量赋值
     */
    public function assign($name, $value = null)
    {
        if (is_array($name)) {
            $this->vars = array_merge($this->vars, $name);
        } else {
            $this->vars[$name] = $value;
        }
        return $this;
    }

    /**
     * 视图过滤
     */
    public function filter(callable $filter = null)
    {
        $this->filter = $filter;
        return $this;
    }

    /**
     * 检查模板是否存在
     */
    public function exists($name)
    {
        return $this->view->exists($name);
    }
}
